package work.comeback.omo.util.configuration.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import work.comeback.omo.util.configuration.interfaces.DatabaseConfigure;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseService {
    private static final Logger logger = LoggerFactory.getLogger(DatabaseService.class);
    private final DatabaseConfigure dbConfig;

    public DatabaseService(DatabaseConfigure dbConfig) {
        this.dbConfig = dbConfig;
    }

    public Connection connect() {
        try {
            return switch (dbConfig.getType()) {
                case "mysql" -> createMysql();
                case "sqlite" -> createSQLite();
                default -> {
                    String err = "Unsupported database type";
                    throw new IllegalArgumentException(err);
                }
            };
        } catch (IllegalArgumentException | SQLException e) {
            String message = "Connection db error: " + e.getMessage();
            logger.error(message);
            throw new RuntimeException(message);
        }
    }

    private Connection createMysql() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver"); // MySQL 8.0 驱动类
        } catch (ClassNotFoundException e) {
            throw new SQLException("MySQL JDBC Driver not found.", e);
        }
        return DriverManager.getConnection(dbConfig.getConnectionUrl(), dbConfig.getUser(), dbConfig.getPassword());
    }

    private Connection createSQLite() throws SQLException {
        try {
            Class.forName("org.sqlite.JDBC"); // 显式注册SQLite驱动
        } catch (ClassNotFoundException e) {
            throw new SQLException("SQLite JDBC Driver not found.", e);
        }
        return DriverManager.getConnection(dbConfig.getConnectionUrl());
    }

    public boolean close(Connection connection) {
        if (connection == null) {
            return true;
        }

        try {
            connection.close();
        } catch (SQLException e) {
            logger.error("Close db error", e);
            return false;
        }

        return true;
    }
}